<template>
  <el-card shadow="never">
    <template #header>
      <div class="flex flex-row items-center justify-between">
        <CardTitle title="交易统计" />
        <!-- 查询条件 -->
        <!-- 查询条件 -->
        <ShortcutDateRangePicker @change="handleTimeRangeChange" />
<!--        <div class="flex flex-row items-center gap-2">-->
<!--          <el-radio-group v-model="timeRangeType" @change="handleTimeRangeTypeChange">-->
<!--            <el-radio-button v-for="[key, value] in timeRange.entries()" :key="key" :label="key">-->
<!--              {{ value.name }}-->
<!--            </el-radio-button>-->
<!--          </el-radio-group>-->
<!--        </div>-->
      </div>
    </template>
    <!-- 折线图 -->
<!--    <Echart :height="300" :options="eChartOptions" />-->

    <el-row :gutter="4" class="mt-3px" justify="space-between">
      <el-col :span="16" class="pr-5px">
        <div class="el-card dawn-radius bg-white" v-loading="zjdfqkShow">
          <el-skeleton :loading="zjdfqkShow" animated>
            <Echart :options="zjdfqkData" style="height:300px"/>
          </el-skeleton>
        </div>
      </el-col>
      <el-col :span="8" class="pr-5px">
        <div class="el-card dawn-radius bg-white" v-loading="zllxShow">
          <div class="flex items-center ml-1! mt-1!">
            <div v-for="(item,index) in payType" :key="index" >
              <div class="flex items-center mr-1!" >
                <el-tag>{{item.name}} <span>￥{{item.value}}</span></el-tag>
              </div>
              <el-divider class="mb-1! mt-1!" />
            </div>

          </div>

          <el-skeleton :loading="zllxShow" animated>
            <Echart :options="zllxData" style="height: 262px"/>
          </el-skeleton>
        </div>
      </el-col>
    </el-row>
  </el-card>
</template>
<script lang="ts" setup>
import dayjs, { Dayjs } from 'dayjs'
import { EChartsOption } from 'echarts'
import * as TradeStatisticsApi from '@/api/mall/statistics/trade'
import * as StaticsApi from '@/api/hosp/statics'
import { fenToYuan } from '@/utils'
import { formatDate } from '@/utils/formatTime'
import { CardTitle } from '@/components/Card'
import * as MemberStatisticsApi from "@/api/mall/statistics/member";
import {getPayCount, getPayTypeCount} from "@/api/hosp/statics";
import { bar_zjdfqk,pie_zllx } from '../echarts-data.ts'
import {set} from "lodash-es";

/** 交易量趋势 */
defineOptions({ name: 'TradeTrendCard' })

const { t } = useI18n() // 国际化

/** 查询数据列表 */
const handleTimeRangeChange = async (times: [dayjs.ConfigType, dayjs.ConfigType]) => {
  loading.value = true
  // 发送时间范围选中事件
  await getOrderCountTrendComparison(times[0], times[1])
  loading.value = false
}

enum TimeRangeTypeEnum {
  WEEK = 7,
  DAY30 = 1,
  MONTH = 30,
  YEAR = 365
} // 日期类型
const timeRangeType = ref(TimeRangeTypeEnum.WEEK) // 日期快捷选择按钮, 默认7天
const loading = ref(true) // 加载中

/** 图表配置 */
const eChartOptions = reactive<EChartsOption>({
  grid: {
    left: 20,
    right: 20,
    bottom: 20,
    top: 80,
    containLabel: true
  },
  legend: {
    top: 50,
    data: []
  },
  series: [],
  toolbox: {
    feature: {
      // 数据区域缩放
      dataZoom: {
        yAxisIndex: false // Y轴不缩放
      },
      brush: {
        type: ['lineX', 'clear'] // 区域缩放按钮、还原按钮
      },
      saveAsImage: { show: true, name: '订单量趋势' } // 保存为图片
    }
  },
  tooltip: {
    trigger: 'axis',
    axisPointer: {
      type: 'cross'
    },
    padding: [5, 10]
  },
  xAxis: {
    type: 'category',
    inverse: true,
    boundaryGap: false,
    axisTick: {
      show: false
    },
    data: [],
    axisLabel: {
      formatter: (date: string) => {
        switch (timeRangeType.value) {
          case TimeRangeTypeEnum.DAY30:
            return formatDate(date, 'MM-DD')
          case TimeRangeTypeEnum.WEEK:
            let weekDay = formatDate(date, 'ddd')
            if (weekDay == '0') weekDay = '日'
            return '周' + weekDay
          case TimeRangeTypeEnum.MONTH:
            return formatDate(date, 'D')
          case TimeRangeTypeEnum.YEAR:
            return formatDate(date, 'M') + '月'
          default:
            return date
        }
      }
    }
  },
  yAxis: {
    axisTick: {
      show: false
    }
  }
}) as EChartsOption

/** 时间范围类型单选按钮选中 */
const handleTimeRangeTypeChange = async () => {
  // 设置时间范围
  let beginTime: Dayjs
  let endTime: Dayjs
  console.table(timeRangeType.value)
  switch (timeRangeType.value) {
    case TimeRangeTypeEnum.WEEK:
      beginTime = dayjs().startOf('week')
      endTime = dayjs().endOf('week')
      break
    case TimeRangeTypeEnum.MONTH:
      beginTime = dayjs().startOf('month')
      endTime = dayjs().endOf('month')
      break
    case TimeRangeTypeEnum.YEAR:
      beginTime = dayjs().startOf('year')
      endTime = dayjs().endOf('year')
      break
    case TimeRangeTypeEnum.DAY30:
    default:
      beginTime = dayjs().subtract(7, 'day').startOf('d')
      endTime = dayjs().endOf('d')
      break
  }
  // 发送时间范围选中事件
  await getOrderCountTrendComparison(beginTime, endTime)
}

const zjdfqkShow = ref(true)
const zjdfqkData = reactive<EChartsOption>(bar_zjdfqk) as EChartsOption
/** 查询订单数量趋势对照数据 */
const getOrderCountTrendComparison = async (
  beginTime: dayjs.ConfigType,
  endTime: dayjs.ConfigType
) => {
  zjdfqkShow.value = true
  loading.value = true
  getPayTypeCount(beginTime,endTime);
  // 查询数据
  const result = await StaticsApi.getPayCount(
    timeRangeType.value,
    beginTime,
    endTime
  )
  console.table(result)
  // set(zjdfqkData, 'title.text','交易统计')
  set(
    zjdfqkData,
    'xAxis.data',
    result.category
  )
  set(
    zjdfqkData,
    'legend.data',
    ['收款', '退款']
  )
  set(zjdfqkData, 'series', [
    {
      name: '收款',
      smooth: true,
      type: 'bar',
      tooltip: {
        valueFormatter: function (value) {
          return value + ' 元';
        }
      },
      data: result.series['收款'],
      animationDuration: 2800,
      animationEasing: 'cubicInOut'
    },
    {
      name: '退款',
      smooth: true,
      type: 'bar',
      itemStyle: {},
      tooltip: {
        valueFormatter: function (value) {
          return value + ' 元';
        }
      },
      data: result.series['退款'],
      animationDuration: 2800,
      animationEasing: 'quadraticOut'
    }
  ])
  zjdfqkShow.value = false
  loading.value = false
}


const payType = ref([])
const zllxShow = ref(true)
const zllxData = reactive<EChartsOption>(pie_zllx) as EChartsOption
/** 查询订单数量趋势对照数据 */
const getPayTypeCount = async (
  beginTime: dayjs.ConfigType,
  endTime: dayjs.ConfigType
) => {
  zllxShow.value = true
  loading.value = true
  // 查询数据
  const result = await StaticsApi.getPayTypeCount(
    timeRangeType.value,
    beginTime,
    endTime
  )
  console.table(result[0]);
  // set(zjdfqkData, 'title.text','交易统计')

  let payTypeData = []
  if (result && result[0]) {
    result[0].forEach(function (el, i) {
      payTypeData.push({value: el.typeAmount, name: el.typeName});
    })
  }
  payType.value = payTypeData;

  set(zllxData, 'series', [
    {
      name: '支付方式',
      type: 'pie',
      radius: [30, 60],
      center: ['50%', '50%'],
      data: payTypeData,
      label: {
        formatter: '{b}: {@2012} 元 ({d}%)'
      },
      emphasis: {
        itemStyle: {
          shadowBlur: 10,
          shadowOffsetX: 0,
          shadowColor: 'rgba(0, 0, 0, 0.5)'
        }
      }
    }
  ])

  zllxShow.value = false
  loading.value = false
}

/** 初始化 **/
onMounted(() => {
  // handleTimeRangeTypeChange()
})
</script>

<style scoped>
:deep(.el-card__body) {
  padding: 5px 10px 10px 10px !important;
}

</style>
